package com.laguille.games.monopoly.commons.player;

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;

import org.apache.commons.lang.Validate;

import com.laguille.games.monopoly.commons.property.Property;

public class HumanPlayer implements Player {

	private final static int INITIAL_CASH = 500;
	
	private final String name;
	private int cash;
	private final Set<Property> ownedProperties;
	
	public HumanPlayer(String name) {
		Validate.notNull(name, "The name can not be null.");
		Validate.notEmpty(name, "The name can not be empty.");
		this.name = name;
		this.ownedProperties = new LinkedHashSet<Property>();
		this.cash = INITIAL_CASH;
	}

	public String getName() {
		return name;
	}

	public Set<Property> getPropertySet() {
		return Collections.unmodifiableSet(ownedProperties);
	}

	public int getCash() {
		return cash;
	}

	public void withdrawCash(int amount) {
		Validate.isTrue(amount > 0);
		cash -= amount;
	}

	public void depositCash(int amount) {
		Validate.isTrue(amount > 0);
		
		cash += amount;
	}
	
	public boolean buyProperty(Property property) {
		
		Validate.notNull(property);
		int buyingPrice = property.getBuyingPrice();
		if (cash >= buyingPrice) {
			withdrawCash(buyingPrice);
			ownedProperties.add(property);
			return true;
		} else {
			return false;
		}
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + cash;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result
				+ ((ownedProperties == null) ? 0 : ownedProperties.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		HumanPlayer other = (HumanPlayer) obj;
		if (cash != other.cash)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (ownedProperties == null) {
			if (other.ownedProperties != null)
				return false;
		} else if (!ownedProperties.equals(other.ownedProperties))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "HumanPlayer [name=" + name + ", cash=" + cash
				+ ", ownedProperties=" + ownedProperties + "]";
	}

}
